#include "ConfigMgr.h"
#include "log.h"
#include <fstream>
#include <filesystem>

const std::string CONFIGNAME = "Config.json";

ConfigMgr::ConfigMgr()
{
    //获取当前执行文件路径
    auto exePath = std::filesystem::current_path();
    exePath /= CONFIGNAME;

    std::ifstream jsonFile(exePath.string());
    if(!jsonFile.is_open())
    {
        log_error("Failed to open config file: {}", exePath.string());
        exit(-1);
    }
    
    std::string jsonString((std::istreambuf_iterator<char>(jsonFile)), std::istreambuf_iterator<char>());
    jsonFile.close();

    auto req = deserialize<Config>(FromString(jsonString));
    if (std::holds_alternative<std::string_view>(req)) 
    {
        log_error("Failed to deserialize Config: {}", std::get<std::string_view>(req));
        exit(-1);
    }

    Config obj = std::get<Config>(req);
    _config = std::make_shared<Config>(obj);
}

void ConfigMgr::Show(std::shared_ptr<Config> config)
{
    log_info("LoginServerPort: {}", config->LoginServerInfo.Port);
    log_info("LoginServerIP: {}", config->LoginServerInfo.IP);
    log_info("GateServerPort: {}", config->GateServerInfo_01.Port);
    log_info("GateServerIP: {}", config->GateServerInfo_01.IP);
    log_info("GateServerPort: {}", config->GateServerInfo_02.Port);
    log_info("GateServerIP: {}", config->GateServerInfo_02.IP);
    log_info("VarifyServerPort: {}", config->VarifyServerInfo.Port);
    log_info("VarifyServerIP: {}", config->VarifyServerInfo.IP);
    log_info("StatusServerPort: {}", config->StatusServerInfo.Port);
    log_info("StatusServerIP: {}", config->StatusServerInfo.IP);
    log_info("StatusServerPoolSize: {}", config->StatusServerInfo.PoolSize);
    log_info("RedisHost: {}", config->RedisInfo.IP);
    log_info("RedisPort: {}", config->RedisInfo.Port);
    log_info("RedisPoolSize: {}", config->RedisInfo.PoolSize);
    log_info("MySqlHost: {}", config->MySqlInfo.IP);
    log_info("MySqlPort: {}", config->MySqlInfo.Port);
    log_info("MySqlUser: {}", config->MySqlInfo.User);
    log_info("MySqlDB: {}", config->MySqlInfo.DB);
    log_info("MySqlPoolSize: {}", config->MySqlInfo.PoolSize);
}

std::shared_ptr<Config> ConfigMgr::GetConfig()
{
    static ConfigMgr instance;
    return instance._config;
}